﻿using PSDLib.Download;
using PSDLib.Models;
using PSDManager.SystemSettings.DeviceTree;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PSDManager.SystemSettings
{
    public partial class FrmDH8900DeviceTree : Form
    {
        public delegate void OnCameraSelectedEventHanlder(PSDLib.Download.ChannelInfo channel, dl_server_config server);
        public event OnCameraSelectedEventHanlder CameraSelected;

        System.Xml.XmlDocument xml = null;
        System.Xml.XmlNodeList searchResult = null;
        int currSearchResultIndex = 0;

        dl_server_config serverConfig = null;
        public PSDLib.Download.ChannelInfo ChannelInfo { get; set; }

        public FrmDH8900DeviceTree()
        {
            InitializeComponent();
        }

        public void Init(dl_server_config server)
        {
            serverConfig = server;

            IDownloadServer dServer = DownloadServerFactory.Create(server.storage_server_type);

            dServer.ServerIP = server.storage_server_ip;
            dServer.ServerPort = server.storage_server_port;
            dServer.ServerUser = server.storage_server_user;
            dServer.ServerPassword = server.storage_server_password;

            if (dServer.Init())
            {
                if (dServer.Login())
                {
                    xml = (dServer as DH8900DownloadServer).GetGroupXml();
                }

                dServer.Logout();
            }

            dServer.Cleanup();

            if (xml != null)
            {
                var deviceList = new List<DH8900Device>();
                var deviceNodes = xml.SelectNodes("Organization/Devices/Device");

                foreach (System.Xml.XmlNode device in deviceNodes)
                {
                    deviceList.Add(new DH8900Device() { Id = device.Attributes["id"].Value, Name = device.Attributes["name"].Value });
                }

                deviceList.Sort();

                foreach (var device in deviceList)
                {
                    TreeNode device_node = new TreeNode();
                    device_node.Text = device.Name;
                    device_node.Name = device.Id;
                    tvwAllChannel.Nodes.Add(device_node);

                    var cameraNodes = xml.SelectNodes("Organization/Devices/Device[@id='" + device.Id + "']/UnitNodes[@streamType]/Channel");

                    foreach (System.Xml.XmlNode camera in cameraNodes)
                    {
                        TreeNode camera_node = new TreeNode();
                        camera_node.Text = camera.Attributes["name"].Value;
                        camera_node.Name = camera.Attributes["id"].Value;
                        device_node.Nodes.Add(camera_node);
                    }
                }
            }

            tvwAllChannel.ExpandAll();
        }

        private void btnAccept_Click(object sender, EventArgs e)
        {
            if (tvwAllChannel.SelectedNode != null && tvwAllChannel.SelectedNode.Level == 1)
            {
                this.ChannelInfo = new PSDLib.Download.ChannelInfo();
                this.ChannelInfo.Id = tvwAllChannel.SelectedNode.Name;
                this.ChannelInfo.Name = tvwAllChannel.SelectedNode.Text;

                if (CameraSelected != null)
                {
                    CameraSelected(this.ChannelInfo, serverConfig);
                }
            }
            else
            {
                MessageBox.Show("请选择一个摄像机通道");
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tvwAllChannel_DoubleClick(object sender, EventArgs e)
        {
            btnAccept_Click(sender, e);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtSearch.Text))
            {
                if (searchResult == null)
                {
                    searchResult = xml.SelectNodes("Organization/Devices/Device/UnitNodes[@streamType]/Channel[contains(@name,'" + txtSearch.Text.Trim() + "')]");
                    currSearchResultIndex = 0;

                    SelectSearchResultNode(searchResult[currSearchResultIndex]);

                    if (searchResult.Count > 1)
                    {
                        btnSearch.Text = "查找下一个";
                    }
                    else
                    {
                        btnSearch.Text = "查找";
                    }
                }
                else
                {
                    if (currSearchResultIndex == searchResult.Count - 1)
                    {
                        if (MessageBox.Show("已无更多匹配项，是否从头开始搜索？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            currSearchResultIndex = 0;
                            SelectSearchResultNode(searchResult[currSearchResultIndex]);
                        }
                    }
                    else
                    {
                        currSearchResultIndex += 1;
                        SelectSearchResultNode(searchResult[currSearchResultIndex]);
                    }
                }
            }
        }

        private void SelectSearchResultNode(System.Xml.XmlNode node)
        {
            var n = tvwAllChannel.Nodes.Find(node.Attributes["id"].Value, true);

            if (n.Length > 0)
            {
                tvwAllChannel.SelectedNode = n[0];
                tvwAllChannel.Select();
            }
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (txtSearch.Text.Length == 0)
            {
                searchResult = null;
                currSearchResultIndex = 0;
                btnSearch.Text = "查找";
            }
        }
    }

   
}
